package filter;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter("/*")
public class GenericEncodingFilter2 implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		final HttpServletRequest req = (HttpServletRequest) request;

		HttpServletRequest myReq = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(),
				req.getClass().getInterfaces(), new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						if ("getParameter".equals(method.getName())) {
							if ("get".equalsIgnoreCase(req.getMethod())) {
								String str = (String) method.invoke(req, args);
								str = new String(str.getBytes("ISO-8859-1"), "UTF-8");
								return str;
							} else if ("post".equalsIgnoreCase(req.getMethod())) {
								req.setCharacterEncoding("UTF-8");	
							}
						}
						return method.invoke(req, args);
					}
				});
		chain.doFilter(myReq, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
